from xtquant import xtdata
import datetime
xtdata.enable_hello = False
# 获取当前交易日所有股票的分钟行情数据
stock_list = xtdata.get_stock_list_in_sector('沪深A股')

def time_to_str(time):
    day = xtdata.get_trading_dates('SH')[-time] # 获取当前交易日
    return datetime.datetime.fromtimestamp(day / 1000).strftime('%Y%m%d')
# print(stock_list )
def my_download(stock_list:list,period:str,start_date = '', end_date = ''):
    '''
    用于显示下载进度
    '''
    import string
    if [i for i in ["d","w","mon","q","y",] if i in period]:
        period = "1d"
    elif "m" in period:
        numb = period.translate(str.maketrans("", "", string.ascii_letters))
        if int(numb) < 5:
            period = "1m"
        else:
            period = "5m"
    elif "tick" == period:
        pass
    else:
        raise KeyboardInterrupt("周期传入错误")
    n = 1
    num = len(stock_list)
    for i in stock_list:
        print(f"当前正在下载 {period} {n}/{num}")
        xtdata.download_history_data(i,period,start_date, end_date)
        n += 1
    print("下载任务结束")



today = time_to_str(1)

# 下载函数，下载完需要注释掉
# my_download(stock_list,"5m",start_date = today, end_date = today)
# my_download(stock_list,"1d",start_date = time_to_str(30), end_date = today)











# 下载数据时把后面注释掉


today = time_to_str(1)


# minute_datas=get_data(stock_list,"5m",start_time = today, end_time = today)
minute_datas = xtdata.get_market_data_ex(field_list=[], stock_list=stock_list, period="5m", start_time=today , end_time=today ,count=-1, fill_data=True)

print(minute_datas)
#遍历所有股票，筛选符合条件的股票
result = []


for name,value in minute_datas.items():
    # 计算当日总成交量
    total_volume = sum(value["volume"])
    # 遍历每分钟数据，计算 5 分钟成交量
    n=0
    a="否"
    h=0
    h1=0
    l=100000000
    print(name,value)
    for i in value["volume"]:
        
        if n>0:
            # 判断是否满足条件
            # print(i / total_volume)
            if total_volume > 0 and i / total_volume > 0.2 :
                # h=max(value["high"])
                try:
                    detail=xtdata.get_instrument_detail(name)
                    for i in value["close"]:
                        if i == detail["UpStopPrice"]:
                            a="是"
                    # if h/value["close"].iloc[-1]>1.05:
                    time_to_str1=time_to_str(30)
                    hist=xtdata.get_market_data_ex(field_list=[], stock_list=[name], period="1d", start_time=time_to_str1, end_time=today, count=-1, fill_data=True)

                    # for x in hist[name]["high"]:
                    #     if x>h1:
                    #         h1=x
                    # for y in hist[name]["low"]:
                    #     if y<l:
                    #         l=y
                    l=min(hist[name]["low"])
                    h1=max(hist[name]["high"])
                    print(l,h1)
                    if l/value["close"].iloc[-1]>0.9 and h1/value["close"].iloc[-1]<1.1:
                        result.append((name,detail["InstrumentName"], value.index[n],round(value["amount"],2).iloc[n],a))
                        break
                        # 找到一次即可，避免重复添加
                except Exception as e:
                    print(e)
        n=n+1
            
# 输出符合条件的股票代码和时间
if result:
    print("符合条件股票列表：")
    for stock_code,name, time, num,a in result:
        print(f"股票代码: {stock_code},名称：{name}, 时间: {time},成交额：{num},是否涨停：{a}")
else:
    print("未找到符合条件的股票")
